<script setup lang="ts">
  import { getCodeApi, loginByMobileApi } from '@/apis/user'
  import { useUserStore } from '@/stores/user'
  import { ref } from 'vue'

  defineOptions({
    options: {
      styleIsolation: 'shared',
    },
  })

  // 是否同意协议
  const isAgree = ref(false)

  // 是否显示验证码
  const isShowCountDown = ref(false)

  // 获取验证码
  const getMobileCode = async () => {
    // 验证手机号
    await form.value?.validateField?.(['mobile'])
    // 发送请求获取验证码
    const res = await getCodeApi({
      mobile: formData.value.mobile,
      type: 'login',
    })
    uni.showToast({ title: '验证码发送成功', icon: 'none' })
    console.log('getCodeApi 测试用的验证码为', res.code)
    // 模拟返回验证码，填写到表单中
    formData.value.code = res.code
    // 开始倒计时
    isShowCountDown.value = true
  }

  // 手机号 + 验证码
  const formData = ref({
    mobile: '13230000066',
    code: '',
  })

  // 表单校验规则
  const formRules: UniHelper.UniFormsRules = {
    mobile: {
      rules: [
        { required: true, errorMessage: '请输入手机号' },
        { pattern: '^1[0-9]{10}$', errorMessage: '请输入正确的手机号' },
      ],
    },
    code: {
      rules: [
        { required: true, errorMessage: '请输入验证码' },
        { pattern: '^[0-9]{6}$', errorMessage: '请输入6位数字验证码' },
      ],
    },
  }

  // 表单组件 ref (Instance 组件实例)
  const form = ref<UniHelper.UniFormsInstance>()
  // 提交表单
  const onSubmit = async () => {
    try {
      // 校验表单所有字段
      await form.value?.validate?.()
      // 判断是否同意用户协议
      if (!isAgree.value) {
        return uni.showToast({ title: '请勾选同意用户协议', icon: 'none' })
      }
      const res = await loginByMobileApi(formData.value)

      // 保存 token 和 id 到 store 中，store 已开启持久化
      const store = useUserStore()
      store.setToken(res.token)
      store.userId =res.id 
      // 成功提示
      uni.showToast({ title: '登录成功', icon: 'success' })
      // 登录成功，跳转首页，注意：这里需要用 switchTab
      uni.switchTab({ url: '/pages/index/index' })
    } catch (error) {
      // 验证失败
      console.log(error)
    }
  }
</script>

<template>
  <uni-forms class="login-form" ref="form" :rules="formRules" :model="formData">
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
        v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
        v-model="formData.code"
      />
      <text class="text-button" v-if="isShowCountDown === false" @click="getMobileCode()">
        获取验证码
      </text>
      <!-- 倒计时组件 -->
      <view class="text-button" v-else>
        <uni-countdown
          :show-day="false"
          :show-hour="false"
          :show-minute="false"
          :second="5"
          @timeup="isShowCountDown = false"
        />
        秒后重新发送
      </view>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" @click="isAgree = !isAgree" color="#16C2A3" />
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button @click="onSubmit()" class="uni-button">登 录</button>
  </uni-forms>
</template>

<style lang="scss">
  @import './styles.scss';
</style>
